package com.eastfair.venueservice.service.impl;

import cn.hutool.core.bean.BeanUtil;
//import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.eastfair.boot.service.SuperServiceImpl;
import com.eastfair.constant.BusinessConstant;
import com.eastfair.core.base.R;
import com.eastfair.core.context.ContextUtil;
import com.eastfair.core.exception.BizException;
import com.eastfair.projectcore.enumeration.MenuAffiliationEnum;
import com.eastfair.venueservice.dao.WorkOvertimeRuleMapper;
import com.eastfair.venueservice.dto.WorkOvertimeRuleDTO;
import com.eastfair.venueservice.dto.WorkOvertimeSpecDTO;
import com.eastfair.venueservice.entity.WorkOvertimeRule;
import com.eastfair.venueservice.enumeration.WorkOvertimeRuleOvertimeTypeEnum;
import com.eastfair.venueservice.exceptioncode.VenueServiceExceptionCode;
import com.eastfair.venueservice.service.WorkOvertimeRuleService;
import com.eastfair.venueservice.service.WorkOvertimeSpecService;
import com.eastfair.venueservice.vo.WorkOvertimeRuleVO;
import com.eastfair.venueservice.vo.WorkOvertimeSpecVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 业务实现类
 * 加班规则
 * </p>
 *
 * @author dqq
 * @date 2023-05-05
 */
@Slf4j
@Service
//@DS("#thread.tenant")
public class WorkOvertimeRuleServiceImpl extends SuperServiceImpl<WorkOvertimeRuleMapper, WorkOvertimeRule> implements WorkOvertimeRuleService {

    @Resource
    private WorkOvertimeSpecService workOvertimeSpecService;

    /**
     * 处理逻辑删除相关处理
     *
     * @param modelList 实体
     * @return 是否成功
     */
    @Override
    protected R<Boolean> handlerRemoveByIdsOfLogic(Collection<WorkOvertimeRule> modelList) {
        modelList.forEach(s -> s.setIsDeleted(BusinessConstant.YES));
        return R.successDef();
    }

    @Override
    protected R<Boolean> handlerSave(WorkOvertimeRule model) {
        model.setProjectId(ContextUtil.getProjectId());
        model.setSubsystemId(ContextUtil.getSubSystemId());
        return R.successDef();
    }

    @Override
    public List<WorkOvertimeRuleVO> listWorkOvertimeRuleVO(WorkOvertimeRuleDTO query) {
        log.info("listWorkOvertimeRuleVO - 查询加班规则列表VO, workOvertimeRuleDTO={}", query);
        List<WorkOvertimeRule> list = listWorkOvertimeRule(query);
        if (list == null || list.isEmpty()) {
            return Collections.emptyList();
        }
        return list
                .stream()
                .map(workOvertimeRule -> BeanUtil.toBean(workOvertimeRule, WorkOvertimeRuleVO.class))
                .collect(Collectors.toList());
    }

    @Override
    public List<WorkOvertimeRule> listWorkOvertimeRule(WorkOvertimeRuleDTO query) {
        QueryWrapper<WorkOvertimeRule> queryWrapper = new QueryWrapper<>();
        queryWrapper
                .lambda()
                .eq(WorkOvertimeRule::getIsDeleted, BusinessConstant.DELETE_NO)
                .eq(query.getOvertimeType() != null, WorkOvertimeRule::getOvertimeType, query.getOvertimeType())
                .eq(query.getBelongSystem() != null, WorkOvertimeRule::getBelongSystem, query.getBelongSystem())
                .eq(query.getHomeId() != null, WorkOvertimeRule::getHomeId, query.getHomeId())
                .eq(query.getExhibitionManageId() != null, WorkOvertimeRule::getExhibitionManageId, query.getExhibitionManageId())
        ;
        return list(queryWrapper);
    }

    @Override
    public List<WorkOvertimeRule> listHomeRuleByOvertimeType(WorkOvertimeRuleOvertimeTypeEnum overtimeType) {
        WorkOvertimeRuleDTO query = new WorkOvertimeRuleDTO();
        query.setBelongSystem(MenuAffiliationEnum.P_COMPOSITE_COURT.getCode());
        query.setOvertimeType(overtimeType);
        return listWorkOvertimeRule(query);
    }

    @Override
    public WorkOvertimeRuleVO getVOById(Long id) {
        WorkOvertimeRule workOvertimeRule = getById(id);
        if (workOvertimeRule == null) {
            return null;
        }
        return BeanUtil.toBean(workOvertimeRule, WorkOvertimeRuleVO.class);
    }

    @Override
    public WorkOvertimeRuleVO getVOByVenueOvertimeType(WorkOvertimeRuleOvertimeTypeEnum overtimeType) {
        log.info("getVOByVenueOvertimeType - 加班类型查询场馆设置的加班规则, overtimeType={}", overtimeType);
        WorkOvertimeRule workOvertimeRule = getByVenueOvertimeType(overtimeType);
        if (workOvertimeRule == null) {
            return null;
        }
        WorkOvertimeRuleVO workOvertimeRuleVO = BeanUtil.toBean(workOvertimeRule, WorkOvertimeRuleVO.class);
        // 添加加班规则
        List<WorkOvertimeSpecVO> workOvertimeSpecList = workOvertimeSpecService.listVOByWorkOvertimeSpec(workOvertimeRuleVO.getId());
        workOvertimeRuleVO.setWorkOvertimeSpecList(workOvertimeSpecList);
        return workOvertimeRuleVO;
    }

    @Override
    public WorkOvertimeRuleVO getVOByVenueOvertimeType(WorkOvertimeRuleOvertimeTypeEnum overtimeType, String specName) {
        WorkOvertimeRuleVO venueRule = getVOByVenueOvertimeType(overtimeType);
        List<WorkOvertimeSpecVO> venueSpecList = venueRule.getWorkOvertimeSpecList();
        if (venueSpecList == null || venueSpecList.isEmpty()) {
           return venueRule;
        }
        // 通过加班申请选择的规格确定规格
        venueSpecList = venueSpecList
                .stream()
                .filter(workOvertimeSpec -> specName.equals(workOvertimeSpec.getSpecName()))
                .collect(Collectors.toList());
        venueRule.setWorkOvertimeSpecList(venueSpecList);
        return venueRule;
    }

    @Override
    public WorkOvertimeRule getByVenueOvertimeType(WorkOvertimeRuleOvertimeTypeEnum overtimeType) {
        WorkOvertimeRuleDTO query = new WorkOvertimeRuleDTO();
        query.setOvertimeType(overtimeType);
        query.setBelongSystem(MenuAffiliationEnum.P_COMPOSITE_VENUE.getCode());
        List<WorkOvertimeRule> list = listWorkOvertimeRule(query);
        if (list == null || list.isEmpty()) {
            return null;
        }
        return list.get(0);
    }

    @Override
    public WorkOvertimeRule getByHomeOvertimeType(WorkOvertimeRuleOvertimeTypeEnum overtimeType, Long exhibitionManageId, Long homeId) {
        WorkOvertimeRuleDTO query = new WorkOvertimeRuleDTO();
        query.setOvertimeType(overtimeType);
        query.setBelongSystem(MenuAffiliationEnum.P_COMPOSITE_COURT.getCode());
        query.setHomeId(homeId);
        query.setExhibitionManageId(exhibitionManageId);
        List<WorkOvertimeRule> list = listWorkOvertimeRule(query);
        if (list == null || list.isEmpty()) {
            return null;
        }
        return list.get(0);
    }

    @Override
    public WorkOvertimeRuleVO getVOByHomeOvertimeType(WorkOvertimeRuleOvertimeTypeEnum overtimeType, Long exhibitionManageId, Long homeId) {
        WorkOvertimeRule workOvertimeRule = getByHomeOvertimeType(overtimeType, exhibitionManageId, homeId);
        if (workOvertimeRule == null) {
            return null;
        }
        WorkOvertimeRuleVO workOvertimeRuleVO = BeanUtil.toBean(workOvertimeRule, WorkOvertimeRuleVO.class);
        // 添加加班规则
        List<WorkOvertimeSpecVO> workOvertimeSpecList = workOvertimeSpecService.listVOByWorkOvertimeSpec(workOvertimeRuleVO.getId());
        workOvertimeRuleVO.setWorkOvertimeSpecList(workOvertimeSpecList);
        return workOvertimeRuleVO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public WorkOvertimeRule saveWorkOvertimeRule(WorkOvertimeRuleDTO workOvertimeRuleDTO) {
        log.info("saveWorkOvertimeRule - 保存加班规则, workOvertimeRuleDTO={}", workOvertimeRuleDTO);
        WorkOvertimeRule workOvertimeRule = BeanUtil.toBean(workOvertimeRuleDTO, WorkOvertimeRule.class);
        save(workOvertimeRule);
        return workOvertimeRule;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveForVenue(WorkOvertimeRuleDTO workOvertimeRuleDTO) {
        log.info("saveForVenue - 场馆保存加班规则, workOvertimeRuleDTO={}", workOvertimeRuleDTO);
        WorkOvertimeRule existRule = getByVenueOvertimeType(workOvertimeRuleDTO.getOvertimeType());
        if (existRule != null) {
            throw BizException.wrap(VenueServiceExceptionCode.WORK_OVERTIME_CONFIG_HAS_EXIST.getCode(), "该加班类型已存在加班规则");
        }
        workOvertimeRuleDTO.setBelongSystem(MenuAffiliationEnum.P_COMPOSITE_VENUE.getCode());
        saveWorkOvertimeRule(workOvertimeRuleDTO);
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveForHome(WorkOvertimeRuleDTO workOvertimeRuleDTO) {
        log.info("saveForHome - 主场保存加班规则, workOvertimeRuleDTO={}", workOvertimeRuleDTO);
        WorkOvertimeRule existRule = getByHomeOvertimeType(workOvertimeRuleDTO.getOvertimeType(), workOvertimeRuleDTO.getExhibitionManageId(), workOvertimeRuleDTO.getHomeId());
        if (existRule != null) {
            throw BizException.wrap(VenueServiceExceptionCode.WORK_OVERTIME_CONFIG_HAS_EXIST.getCode(), "该加班类型已存在加班规则");
        }
        // 保存加班规则
        workOvertimeRuleDTO.setBelongSystem(MenuAffiliationEnum.P_COMPOSITE_COURT.getCode());
        WorkOvertimeRule workOvertimeRule = saveWorkOvertimeRule(workOvertimeRuleDTO);
        // 批量保存加班规格
        List<WorkOvertimeSpecDTO> workOvertimeSpecList = workOvertimeRuleDTO.getWorkOvertimeSpecList();
        workOvertimeSpecService.saveBatch(workOvertimeSpecList, workOvertimeRule.getId());
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public WorkOvertimeRule updateWorkOvertimeRule(WorkOvertimeRuleDTO workOvertimeRuleDTO) {
        log.info("updateWorkOvertimeRule - 更新加班规则, workOvertimeRuleDTO={}", workOvertimeRuleDTO);
        WorkOvertimeRule workOvertimeRule = BeanUtil.toBean(workOvertimeRuleDTO, WorkOvertimeRule.class);
        updateById(workOvertimeRule);
        return workOvertimeRule;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public WorkOvertimeRule updateVenueWorkOvertimeRule(WorkOvertimeRuleDTO venueWorkOvertimeRuleDTO) {
        log.info("updateVenueWorkOvertimeRule - 场馆更新加班规则, workOvertimeRuleDTO={}", venueWorkOvertimeRuleDTO);
        WorkOvertimeRule venueRule = updateWorkOvertimeRule(venueWorkOvertimeRuleDTO);
        updateHomeRuleByVenue(venueRule);
        return venueRule;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateHomeRuleByVenue(WorkOvertimeRule venueRule) {
        // 查询该加班类型下 主场所有的加班规则
        List<WorkOvertimeRule> homeRuleList = listHomeRuleByOvertimeType(venueRule.getOvertimeType());
        if (homeRuleList == null || homeRuleList.isEmpty()) {
            return false;
        }
        homeRuleList.forEach(homeRule -> {
            homeRule.setTimeUnit(venueRule.getTimeUnit());
            homeRule.setSubmitPeriodOneBegin(venueRule.getSubmitPeriodOneBegin());
            homeRule.setSubmitPeriodOneEnd(venueRule.getSubmitPeriodOneEnd());
            homeRule.setSubmitPeriodTwoBegin(venueRule.getSubmitPeriodTwoBegin());
            homeRule.setSubmitPeriodTwoEnd(venueRule.getSubmitPeriodTwoEnd());
        });
        updateBatchById(homeRuleList);
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean removeRuleById(Long id) {
        log.info("removeRuleById - id删除加班规则, id={}", id);
        WorkOvertimeRule workOvertime = getById(id);
        if (workOvertime == null) {
            return false;
        }
        List<WorkOvertimeRule> list = new ArrayList<>();
        list.add(workOvertime);
        removeByIdsOfLogic(list);
        // 移除加班规格
        return workOvertimeSpecService.removeByWorkOvertimeRuleId(workOvertime.getId());
    }
}
